<?php

namespace App\Http\Controllers\Site\Custom\Provider;

use App\B2BProject\Custom\StoreNavigation;
use App\B2BProject\Site\HelperControllerBuildTrait;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class StoreNavigationController extends Controller
{
    use HelperControllerBuildTrait;

    public function getIndex(Request $request)
    {
        if ($request->ajax()) {
            if ($id = $request->navid) {
                $nav = StoreNavigation::findOrFail($id);

                return response()->json([
                    'data' => [
                        'name' => $nav->title,
                        'showFlag' => $nav->display,
                        'textarea' => $nav->content
                    ]
                ]);
            }

            $store = \Auth::user()->store;

            if ($store->nav()->count() == 0) {
                foreach (['招商加盟', '公司简介'] as $title) {
                    $navInstance = new StoreNavigation();

                    $navInstance->title   = $title;
                    $navInstance->content = '';

                    $navInstance->save();

                    $store->nav()->save($navInstance);
                }
            }

            $navs = $store->nav;

            $data = ['data' => []];

            foreach ($navs as $nav) {
                $data['data'][] = [
                    'id'       => $nav->id,
                    'name'     => $nav->title,
                    'showFlag' => $nav->display,
                ];
            }

            return response()->json($data);
        }

        return view('host/custom/provider/navigation/index');
    }

    public function putIndex(Request $request)
    {
        // TODO 需要表单验证
        $id = $request->navid;

        $nav = StoreNavigation::findOrFail($id);

        $nav->title = $request->input('name');
        $nav->display = $request->input('show');
        $nav->content = $request->input('text');

        $nav->save();

        $request->navid = null;

        return $this->getIndex($request);
    }
}
